package it.univpm.diiga.memorysim.views;


import java.util.ArrayList;

import it.univpm.diiga.memorysim.data.Situation;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.part.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;




public class OutputTable extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "it.univpm.diiga.memorysim.views.OutputTable";

	private TableViewer viewer;
	private ArrayList<String[]> Table= new ArrayList<String[]>();

	 
	class ViewContentProvider implements IStructuredContentProvider {
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			return null;
		}
	}
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			return getText(obj);
		}
		public Image getColumnImage(Object obj, int index) {
			return getImage(obj);
		}
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}
	}
	class NameSorter extends ViewerSorter {
	}

	public OutputTable() {
	}

	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		createData();
		createColumns(parent, viewer);
		hookDoubleClickAction();
	}


	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
				try {
					window.getActivePage().showView(OutputSimulation.ID, "proc mem", IWorkbenchPage.VIEW_ACTIVATE);
				} catch (PartInitException e1) {
					MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
				}
				TableItem selection=(viewer.getTable().getSelection())[0];
				int index=Integer.parseInt(selection.getText(0));
				int pid=Integer.parseInt(selection.getText(4));
				String pagin=selection.getText(2);
				String pagout=selection.getText(3);
				if(pagin=="") pagin="-2";
				if(pagout=="") pagout="-2";
				int a=Situation.getMemAddress(index,pid, Integer.parseInt(pagin));
				int b=Situation.getSWAPAddress(index,pid, Integer.parseInt(pagout));
				OutputSimulation.setPageFoult(pid,a,b);
				OutputSimulation.setNewLabels(Situation.getMemLabels(index),Situation.getSWAPLabels(index));			
			}
		});
	}


	// This will create the columns for the table
	private void createColumns(final Composite parent, final TableViewer viewer) {
		final Menu headerMenu = new Menu(parent);
		String[] titles = { "Indice", "Evento", "SwapOut","SwapIn", "Processo" ,"Tempo"};
		int[] bounds = { 80, 500, 60, 60 ,60,60};

		for (int i = 0; i < titles.length; i++) {
			final TableViewerColumn viewerColumn = new TableViewerColumn(
					viewer, SWT.NONE);
			final TableColumn column = viewerColumn.getColumn();
			column.setText(titles[i]);
			column.setWidth(bounds[i]);
			column.setResizable(true);
			createMenuItem(headerMenu, column); // Create the menu item for this
												// column
			column.setMoveable(true);

			// Setting the right sorter
			column.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					int dir = viewer.getTable().getSortDirection();
					if (viewer.getTable().getSortColumn() == column) {
						dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
					} else {

						dir = SWT.DOWN;
					}
					viewer.getTable().setSortDirection(dir);
					viewer.getTable().setSortColumn(column);
					viewer.refresh();
				}
			});
		}
		final Table table = viewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		for(int h=0;h<Table.size();h++){
			String[] data = Table.get(h);
			TableItem prova= new TableItem(table,0);
			prova.setText(0, data[0]);
			prova.setText(1, data[1]);
			prova.setText(2,data[2]);
			prova.setText(3,data[3]);
			prova.setText(4,data[4]);
			prova.setText(5,data[5]);
		}

		table.addListener(SWT.MenuDetect, new Listener() {
			public void handleEvent(Event event) {
				table.setMenu(headerMenu);
			}
		});

	}

	private void createMenuItem(Menu parent, final TableColumn column) {
		final MenuItem itemName = new MenuItem(parent, SWT.CHECK);
		itemName.setText(column.getText());
		itemName.setSelection(column.getResizable());
		itemName.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (itemName.getSelection()) {
					column.setWidth(150);
					column.setResizable(true);
				} else {
					column.setWidth(0);
					column.setResizable(false);
				}
			}
		});

	}
	

	public void setFocus() {
		viewer.getControl().setFocus();
	}
	
	public void createData(){
			for(int i=0;i<Situation.getTable().size();i++){
				String event=Situation.getTable().get(i).getEventType()+" ";
				String pagIn="";
				String pagOut="";
				String pid="";
				String time="";
				if(Situation.getTable().get(i).getEventPID()>0) pid+=Situation.getTable().get(i).getEventPID();
				if(Situation.getTable().get(i).getPageIn()>0) pagIn+=Situation.getTable().get(i).getPageIn();
				if(Situation.getTable().get(i).getPageOut()>0) pagOut+=Situation.getTable().get(i).getPageOut();
				time+=Situation.getTable().get(i).getTime();
				if(pid!="") event+=" processo "+pid;
				if(pagIn!="") event+=" pagina "+pagIn;
				if(pagOut!="") event+=" sostituisci con "+pagOut;
				String[] dati= new String[]{i+"",event,pagIn,pagOut,pid,time};
				Table.add(dati);	
			}
	}
	

}